EntityService = require './EntityService'
EntityServiceCache = require './EntityServiceCache'
log = require('../log')

headers = {}

gLoad = ->
    headers = {}
    heads = yield from EntityService.gList({}, {entityName: "F_PageHead", pageSize: -1, withoutTotal: true})
    for head in heads
        headers[head.key] = head

exports.gInit = ->
    yield from gLoad()

    onChange = (ctx, entityName)->
        if entityName == 'F_PageHead'
            yield from gLoad()

    EntityServiceCache.onUpdatedOrRemoved onChange

    EntityServiceCache.onEntityCreated onChange

exports.getPageHead = (key)->
    title = null
    keyword = null
    while key.length
        h = headers[key]
        if h
            title = title || h.title
            keyword = keyword || h.keyword
            return {title, keyword} if title and keyword
        i = key.lastIndexOf("/")
        return null unless i >= 0
        key = key.slice(0, i - 1)

jade = require '../jade'
jade.jadeLocals.getPageHead = exports.getPageHead





